// 获取元素
function $(dom) {
  return document.querySelector(dom)
}
// 获取全部元素
function $2(dom) {
  return document.querySelectorAll(dom)
}
// 本地存储
function save(arr, str) {
  localStorage.setItem(str, JSON.stringify(arr))
}

function arr_loaded(arr, indexSave) {
  arr.forEach((item, index) => {
    indexArr.push({ index: indexSave[index] ? indexSave[index].index : 'false' })
  })
  arr.forEach(item => rotateArr.push({ rotate: item.rotateRandom }))
}

let arrs = localStorage.getItem('arrValue') === null ? [] : JSON.parse(localStorage.getItem('arrValue'))
let TimeSave = localStorage.getItem('arrTime') === null ? [] : JSON.parse(localStorage.getItem('arrTime'))
let nameSave = localStorage.getItem('arrName') === null ? [] : JSON.parse(localStorage.getItem('arrName'))
let rankingNum = localStorage.getItem('rankingNum') === null ? [] : JSON.parse(localStorage.getItem('rankingNum'))
let suspendSave = localStorage.getItem('suspend') === null ? [] : JSON.parse(localStorage.getItem('suspend'))
let borderSave = localStorage.getItem('border') === null ? [] : JSON.parse(localStorage.getItem('border'))
let rotateSave = localStorage.getItem('rotate') === null ? [] : JSON.parse(localStorage.getItem('rotate'))
let indexSave = localStorage.getItem('index') === null ? [] : JSON.parse(localStorage.getItem('index'))
let rankingSave = localStorage.getItem('ranking') === null ? [] : JSON.parse(localStorage.getItem('ranking'))
let ranking = []
let obj = {}
let arrTime = [{}]
let arrName = [{}]
let arrRanking = [{}]
let arrSuspend = [{}]

// 记录拼图的数组
let indexArr = []

// 记录旋转的数组
let rotateArr = []


// 图片拖拽导入功能
let box = $('.boxs')

box.ondragover = function (e) {
  e.preventDefault();
}
box.ondrop = function (e) {
  e.preventDefault();
  let f = e.dataTransfer.files[0];//获取到第一个上传的文件对象
  let fr = new FileReader();//实例FileReader对象
  fr.readAsDataURL(f);//把上传的文件对象转换成url
  fr.onload = function (e) {
    let Url = this.result;//上传文件的URL
    $(".preview").style.backgroundImage = "url('" + Url + "')"
  }
}

// 点击开始
$(".startBtn").onclick = function () {
  if ($('#name').value !== '') {
    // 启动模式关闭
    $('#start').style.display = "none"
    // 名字赋值
    $('#playername').innerHTML = $('#name').value
    obj['name'] = $('#name').value
    obj['ranking'] = $("#difficult").value
    arrName[0]['name'] = $('#name').value
    arrRanking[0]['ranking'] = $("#difficult").value
    save(arrRanking, 'rankingNum')
    save(arrName, 'arrName')
    created($("#difficult").value)
    startTime()
  } else {
    alert('用户名不能为空!')
  }
}
// 判断本地存储的数组
if (arrs.length !== 0) {
  // 恢复地图
  createdMap(arrs)
  // 恢复时间
  if (TimeSave.length !== 0) {
    second = Number(TimeSave[0]['second'])
    minute = Number(TimeSave[0]['minute'])
  }
  startTime(second, minute)
  // 名字赋值
  $('#playername').innerHTML = nameSave[0].name
  $('#start').style.display = "none"
  // 恢复暂停
  if (suspendSave.length !== 0) {
    if (suspendSave[0]['pause'] == 'RESUME') {
      $('#puzzle').style.opacity = 0
      $('#puzzleDestination').style.opacity = 0
      $('.pauseBtn').innerHTML = 'RESUME'
      timer = clearInterval(timer)
    }
  }
} else {
  $('#start').style.display = "block"
}
var timer
var second = 0
var minute = 0
// 计时
function startTime(seconds, minutes) {
  let timerNode = $("#timer")
  if (seconds || minutes) {
    timer = setInterval(() => {
      if (seconds >= 60) {
        minutes += 1
        seconds = 0
      } else {
        seconds++
      }
      arrTime[0]['minute'] = `${minutes}`
      arrTime[0]['second'] = `${seconds}`
      save(arrTime, 'arrTime')
      timerNode.innerHTML = `${minutes}:${seconds}`
    }, 1000);
  } else {
    timer = setInterval(() => {
      if (second >= 60) {
        minute += 1
        second = 0
      } else {
        second++
      }
      arrTime[0]['minute'] = `${minute}`
      arrTime[0]['second'] = `${second}`
      save(arrTime, 'arrTime')
      timerNode.innerHTML = `${minute}:${second}`
    }, 1000);

    // let s = 0;
    // timer = setInterval(()=>{
    //   s++
    //   second = Math.floor(s/10%60) < 10 ? '0' + Math.floor(s/10%60) :  Math.floor(s/10%60)
    //   minute = Math.floor(s/10/60) < 10 ? '0' + Math.floor(s/10/60) : Math.floor(s/10/60) 
    //   timerNode.innerHTML = `${minute}:${second}`
    // },100);

  }
}
// 创建拼图
function created(num) {
  // 块数
  let createdNum
  // 获取图片
  let bgImg = window.getComputedStyle($('.preview'), null)['background-image']
  // 获取容器大小
  let size = Number(window.getComputedStyle($('#puzzle'), null)['width'].substring(0, window.getComputedStyle($('#puzzle'), null)['width'].length - 2))
  let arr = []
  // 选择关卡
  if (num == 1) {
    createdNum = 2
  } else if (num == 2) {
    createdNum = 3
  } else if (num == 3) {
    createdNum = 4
  }

  for (let i = 0; i < createdNum; i++) {
    for (let j = 0; j < createdNum; j++) {
      let rotate = Math.floor(Math.random() * 4) * 90
      arr.push({
        // 记录x, y的位置
        x: j,
        y: i,
        bgX: size / createdNum * j,
        bgY: size / createdNum * i,
        // 记录位置组
        position: [
          {
            x: size / createdNum * j,
            y: size / createdNum * i
          }
        ],
        // 添加随机角度
        rotateRandom: rotate,
        width: size / createdNum,
        height: size / createdNum,
        top: size / createdNum * i,
        left: size / createdNum * j,
        bgImg,
        // 随机位置组
        positionArr: [],
        border: '',
      })
    }
  }
  // 生成随机位置
  let = positionArr = []
  arr.forEach(item => positionArr.push(item.position))
  positionArr.sort(randomsort)
  // 将随机过的数组添加进原数组
  arr.forEach((item, index) => item.positionArr = positionArr[index])
  save(arr, 'arrValue')
  arrs.length !== 0 ? createdMap(arrs) : createdMap(arr)
}
function createdMap(arr) {

  arr.forEach((item, index) => {
    // 渲染左边格子
    $("#puzzle").innerHTML += `
      <div class="item ${borderSave.length !== 0 ? borderSave[index].border : ''}" x="${item.x}" y="${item.y}" index="${index}" rotate="${item.rotateRandom}" style="
        position: absolute;
        width:${item.width}px;
        height:${item.height}px;
        top: ${item.top}px;
        left: ${item.left}px;
        opacity: ${indexSave.length !== 0 && indexSave[index].index === 'true' ? 0 : 1
      }
      "></div>`

    //渲染右边格子
    $("#puzzleDestination").innerHTML += `
      <div class="item2" x="${item.x}" y="${item.y}" index="${index}" style="
        position: absolute;
        width:${item.width}px;
        height:${item.height}px;
        top: ${item.top}px;
        left: ${item.left}px;
      "></div>`

    // 位置重新定位
    $2(".item")[index].style.top = item.positionArr[0].x + 'px'
    $2(".item")[index].style.left = item.positionArr[0].y + 'px'

    // 左边拼图背景图片
    $2(".item")[index].style.cssText += `
    background:${item.bgImg} -${item.bgX}px -${item.bgY}px;
    transform: rotate(${rotateSave.length !== 0 ? rotateSave[index].rotate : item.rotateRandom}deg);
    background-size: 500px 500px;`;
    // 右边拼图背景图片
    $2(".item2")[index].style.cssText += `
    background:${item.bgImg} -${item.bgX}px -${item.bgY}px;
    background-size: 500px 500px;
    opacity: ${indexSave.length !== 0 && indexSave[index].index === 'true' ? 1 : 0.5}`;
  })

  arr_loaded(arr, indexSave);

}
// 打乱数组的函数
function randomsort() {
  return Math.random() > .5 ? -1 : 1;
  //用Math.random()函数生成0~1之间的随机数与0.5比较，返回-1或1
}

// 重新开始
$(".restartBtn").onclick = function () {
  again()
}

function again() {
  // 启动模式关闭
  $('#start').style.display = "block"
  localStorage.removeItem('arrValue')
  localStorage.removeItem('arrTime')
  localStorage.removeItem('arrName')
  localStorage.removeItem('border')
  localStorage.removeItem('rotate')
  localStorage.removeItem('index')
  localStorage.removeItem('suspend')
  localStorage.removeItem('rankingNum')
  location.reload()
}

// 暂停
$('.pauseBtn').onclick = function () {
  if (this.innerHTML == 'PAUSE') {
    $('#puzzle').style.opacity = 0
    $('#puzzleDestination').style.opacity = 0
    arrSuspend[0]['pause'] = 'RESUME'
    save(arrSuspend, 'suspend')
    this.innerHTML = 'RESUME'
    timer = clearInterval(timer)
  } else {
    $('#puzzle').style.opacity = 1
    $('#puzzleDestination').style.opacity = 1
    arrSuspend[0]['pause'] = 'PAUSE'
    save(arrSuspend, 'suspend')
    this.innerHTML = 'PAUSE'
    if (TimeSave.length !== 0) {
      second = Number(TimeSave[0]['second'])
      minute = Number(TimeSave[0]['minute'])
    }
    startTime(second, minute)
  }
}

// 点击格子
$("#puzzle").addEventListener('click', function (e) {
  let target = e.target
  let borderArr = []
  $2('.item2').forEach(item => borderArr.push({ border: '' }))
  if (target.className.indexOf('item') > -1) {
    let index = Number(target.getAttribute('index'))
    borderArr[index].border = 'border'
    save(borderArr, 'border')
    $2(".item").forEach(item => item.classList.remove('border'))
    target.classList.add('border')
    // 当前格子的出生位置
    let leftTop = { x: target.style.left, y: target.style.top }
    rotate(target)
    drag(target)
    RightMove(target, leftTop)
  }
})

// 左右旋转
function rotate(target) {
  let rotate = Number(target.getAttribute('rotate'))
  document.onkeydown = function (e) {
    let index = target.getAttribute('index')
    // 37左边 39右边
    if (e.keyCode == 37) {
      if (rotate < 90) {
        rotate = 270
      } else {
        rotate -= 90
      }
    } else if (e.keyCode == 39) {
      if (rotate > 270) {
        rotate = 90
      } else {
        rotate += 90
      }
    }
    // 记录旋转值
    if (arrs.length !== 0) {
      rotateArr[index].rotate = rotate
      save(rotateArr, 'rotate')
    }
    target.style.transform = `rotate(${rotate}deg)`
    target.setAttribute('rotate', rotate)
  }
}

// 拖拽
function drag(target, leftTop) {
  var tag = target;
  var clientW = document.body.clientWidth;
  var clientH = document.body.clientHeight;
  tag.onmousedown = function (e) {

    var e = e || window.event;

    var disX = tag.offsetLeft;
    var disY = tag.offsetTop;

    var x = e.pageX - disX;
    var y = e.pageY - disY;

    var width = tag.offsetWidth;
    var height = tag.offsetHeight;
    document.onmousemove = function (e) {
      var e = e || window.event;
      var left = e.pageX - x;
      var top = e.pageY - y;
      if (left < 0) {
        left = 0;
      }
      if (top < 0) {
        top = 0;
      }
      if (left >= clientW - width) {
        left = clientW - width;
      }
      if (top >= clientH - height) {
        top = clientH - height;
      }
      tag.style.left = left + "px";
      tag.style.top = top + "px";
    }
    return false
  }

  document.onmouseup = function () {
    document.onmousedown = null;
    document.onmousemove = null;
  };
}


// 在右边拼图中移动触发
function RightMove(targetNode, leftTop) {
  $('#puzzleDestination').addEventListener('mouseup', function (e) {
    let target = e.target
    // 左边格子的数据
    let itemX = targetNode.getAttribute('x')
    let itemY = targetNode.getAttribute('y')
    let itemRotate = Number(targetNode.getAttribute('rotate'))
    // 右边格子的数据
    let item2X = target.getAttribute('x')
    let item2Y = target.getAttribute('y')
    if (itemX === item2X && itemY === item2Y && (itemRotate == 360 || itemRotate == 0)) {
      let itemIndex = targetNode.getAttribute('index')

      indexArr[itemIndex].index = 'true'
      save(indexArr, 'index')

      targetNode.remove()
      target.style.opacity = 1

      if (indexArr.every(item => item.index == 'true')) {
        if (!obj['name'] && !obj['ranking']) {
          obj['name'] = nameSave[0].name
          obj['ranking'] = rankingNum[0].ranking
        }
        obj['time'] = arrTime[0]
        obj['time2'] = arrTime[0]['minute'] + arrTime[0]['second']
        timer = clearInterval(timer)
        if (rankingSave.length !== 0) {
          rankingSave.push(obj)
          save(rankingSave, 'ranking')
        } else {
          ranking.push(obj)
          save(ranking, 'ranking')
        }
        $('#end').style.display = "block"
        ranking_List()
      }
    } else {
      targetNode.style.left = leftTop.x
      targetNode.style.top = leftTop.y
      document.onmousedown = null;
      document.onmousemove = null;
    }
  })
}
$('.restartRankBtn').onclick = function () {
  again()
}
ranking_List()
// 排行榜
function ranking_List() {
  let obj = rankingSave[rankingSave.length - 1]
  let arr = []
  let indexs
  if (obj['ranking'] === '1') {
    // 简单的三条数据
    let easyArr = rankingSave.filter(item => item.ranking == '1')
    easyArr.sort(function (a, b) {
      return a.time2 - b.time2
    })
    arr = easyArr.filter((item, index) => {
      if (index < 3) return item
    })
    easyArr.forEach((item, index) => {
      if (item == obj) {
        return indexs = index
      }
    })
    let flg = false
    arr.forEach((item, index) => {
      if (obj['time'].minute <= item['time'].minute) {
        if (obj['time'].second < item['time'].second || obj['time'].minute < item['time'].minute) {
          flg = true
        }
      }
    })
    !flg ? arr.push(obj) : ''
  } else if (obj['ranking'] === '2') {
    // 中等的三条数据
    let mediumArr = rankingSave.filter(item => item.ranking == '2')
    mediumArr.sort(function (a, b) {
      return a.time2 - b.time2
    })
    arr = mediumArr.filter((item, index) => {
      if (index < 3) return item
    })
    mediumArr.forEach((item, index) => {
      if (item == obj) {
        return indexs = index
      }
    })
    let flg = false
    arr.forEach((item, index) => {
      if (obj['time'].minute <= item['time'].minute) {
        if (obj['time'].second < item['time'].second || obj['time'].minute < item['time'].minute) {
          flg = true
        }
      }
    })
    !flg ? arr.push(obj) : ''
  } else if (obj['ranking'] === '3') {
    // 中等的三条数据
    let hardArr = rankingSave.filter(item => item.ranking == '3')
    hardArr.sort(function (a, b) {
      return a.time2 - b.time2
    })
    arr = hardArr.filter((item, index) => {
      if (index < 3) return item
    })
    hardArr.forEach((item, index) => {
      if (item == obj) {
        return indexs = index
      }
    })
    let flg = false
    arr.forEach((item, index) => {
      if (obj['time'].minute <= item['time'].minute) {
        if (obj['time'].second < item['time'].second || obj['time'].minute < item['time'].minute) {
          flg = true
        }
      }
    })
    !flg ? arr.push(obj) : ''
  }

  // 合成数组再进行排序
  // arr = [...easyArr, ...mediumArr, ...hardArr]
  // arr.sort(function (a, b) {
  //   return b.ranking - a.ranking ? b.ranking - a.ranking : a.time2 - b.time2
  // })

  $(".tbody").innerHTML = ''
  arr.forEach((item, index) => {
    $(".tbody").innerHTML += `
      <tr>
        <td>${index > 2 ? indexs + 1 : index + 1}</td>
        <td>${item.ranking == '3' ? 'HARD' : '' || item.ranking == '2' ? 'MEDIUM' : '' || item.ranking == '1' ? 'EASY' : ''}</td>
        <td>${item.name}</td>
        <td>${item.time['minute']}:${item.time['second']}</td>
      </tr>
    `
  })
}